package org.chench.extra;

import org.zeromq.ZContext;
import org.zeromq.ZMQ;

import java.util.Random;

/**
 * 使用"发布-订阅"模式
 * 使用一个天意预报主动推送的例子
 * @author chench9@lenovo.com
 * @desc org.chench.extra.PubServer
 * @date 3/20/19 11:22 AM
 */
public class PubServer {
    public static void main(String[] args) {
        startPubServer();
    }

    private static void startPubServer() {
        try(ZContext context = new ZContext()) {
            // 创建"发布"模式Socket
            ZMQ.Socket publisher = context.createSocket(ZMQ.PUB);
            publisher.bind("tcp://*:5555");

            Random random = new Random(System.currentTimeMillis());
            while(!Thread.currentThread().isInterrupted()) {
                // 随机产生一个天气预报数据,发布给订阅的客户端
                int zipcode, temperature, relhumidity;
                zipcode = 10000;
                temperature = random.nextInt(215) - 80 + 1;
                relhumidity = random.nextInt(50) + 10 + 1;
                //  Send message to all subscribers
                String update = String.format("%05d %d %d", zipcode, temperature, relhumidity);
                publisher.send(update, 0);

                // 每隔1秒发布一个天气消息
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }


}
